#!/bin/sh

set -xe

if [ "${branch}" = "master" ]; then
    branch="rawhide"
fi

# Find the base dir
base_dir="$(dirname $0)/.."
HOMEDIR=$(pwd)

function clean_up {
    set +e
    # Logs need to be in a specific place to be picked up.
    sudo cp -f $(ls -tr /${HOMEDIR}/output/images/fedora-atomic-*.qcow2 | tail -n 1) ${HOMEDIR}/output/logs/untested-atomic.qcow2
    sudo mv ${HOMEDIR}/output/logs ${HOMEDIR}
}

trap clean_up EXIT SIGHUP SIGINT SIGTERM

# Make sure logs are empty so we don't report previous build
# if we fail
if [ -e "${HOMEDIR}/output/logs" ]; then
    sudo rm -rf ${HOMEDIR}/output/logs >/dev/null 2>&1
    echo "rm -rf ${HOMEDIR}/output/logs rc:$?"
fi
mkdir -p ${HOMEDIR}/output

pushd $base_dir/config/Dockerfiles/rsync
sudo docker build -t rsync-container .
popd

pushd $base_dir/config/Dockerfiles/ostree-image-compose
sudo docker build -t ostree-image-compose-container .
popd

sudo docker run --privileged --cap-add=SYS_ADMIN -v ${HOMEDIR}/output:/home/output -e rsync_paths="netinst ostree images" -e rsync_from="${RSYNC_USER}@${RSYNC_SERVER}::${RSYNC_DIR}/${branch}/" -e rsync_to="/home/output/" -e RSYNC_PASSWORD="$RSYNC_PASSWORD" rsync-container

sudo docker run --storage-opt size=20G --privileged -e 'container=docker' -v /sys/fs/cgroup:/sys/fs/cgroup:rw -v ${HOMEDIR}/output:/home/output -e branch="${branch}" -e HTTP_BASE="${HTTP_BASE}" ostree-image-compose-container

sudo docker run --privileged --cap-add=SYS_ADMIN -v ${HOMEDIR}/output:/home/output -e rsync_paths="netinst" -e rsync_to="${RSYNC_USER}@${RSYNC_SERVER}::${RSYNC_DIR}/${branch}/" -e rsync_from="/home/output/" -e RSYNC_PASSWORD="$RSYNC_PASSWORD" rsync-container

# Only rsync image to artifacts.ci.centos.org if PUSH_IMAGE = true
if [ "${PUSH_IMAGE}" = "true" ]; then
     sudo docker run --privileged --cap-add=SYS_ADMIN -v ${HOMEDIR}/output:/home/output -e rsync_paths="images" -e rsync_to="${RSYNC_USER}@${RSYNC_SERVER}::${RSYNC_DIR}/${branch}/" -e rsync_from="/home/output/" -e RSYNC_PASSWORD="$RSYNC_PASSWORD" rsync-container
fi
